package com.ruoyi.web.controller.screenSave;


import com.alibaba.druid.util.StringUtils;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.resource.service.IFileOperator;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/screensave")
public class ScreenSaveController {



    @Value("${screenSave.root}")
    private String folder;

    @Autowired
    IFileOperator iFileOperator;

    /**
     *
     * @param browserId 浏览器id
     * @param file 上传的图片名
     * @return
     */
    @PostMapping("/{browserId}")
    public AjaxResult postScreenSave(@PathVariable Integer browserId, @RequestParam("image")MultipartFile file){
        if(file.isEmpty()){
            return new AjaxResult(400,"图片为空");
        }

        if(!"image/png".equals(file.getContentType())&& !"image/jpeg".equals(file.getContentType())) {
            return new AjaxResult(400, "仅支持jpeg和png");
        }

        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String type = fileName.substring(fileName.lastIndexOf('.'));
        /** 删除原有的文件 */
        iFileOperator.DeleteScreenSaveByBrowserId(browserId);
        /** 文件保存路径 */
        String newPath = folder + '/' + browserId + type;
        try {
            file.transferTo(new File(newPath));
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResult(500,"服务器发生异常");
        }
        return new AjaxResult(200, "上传成功");
    }

    @GetMapping("/{browserId}")
    public ResponseEntity<ByteArrayResource> getScreenSave(@PathVariable Integer browserId){
        String potentialSuffixJPG = ".jpg";
        String potentialSuffixPNG = ".png";
        Path imagePath = Paths.get(folder + '/' +browserId + potentialSuffixPNG);
        if(!Files.exists(imagePath)){
             imagePath = Paths.get(folder + '/' +browserId + potentialSuffixJPG);
        }
        if(!Files.exists(imagePath)){
            return ResponseEntity.notFound().build();
        }
        try {
            byte[] imageContent = Files.readAllBytes(imagePath);
            ByteArrayResource resource = new ByteArrayResource(imageContent);
            HttpHeaders headers = new HttpHeaders();
            if(imagePath.getFileName().endsWith("jpg")) {
                headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE);
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=" + browserId + ".jpg");
            }
            else {
                headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE);
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=" + browserId + ".png");
            }
            headers.add(HttpHeaders.CACHE_CONTROL, "max-age=86400");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);

        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.internalServerError().build();
        }

    }
}


